package com.tomato.wangzh.grpc.server;

import com.tomato.wangzh.grpc.common.HelloServiceGrpc;
import io.grpc.Server;
import io.grpc.ServerBuilder;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

/**
 * <p>
 * Copyright: (C), 2021/6/4 14:53
 * <p>
 * <p>
 * Company: Information & Data Security Solutions Co., Ltd.
 *
 * @author neil.wang@idss-cn.com
 * @version 1.0
 */
public class GrpcServer {

    private static final Logger logger = Logger.getLogger(GrpcServer.class.getName());
    /**
     * grpc server
     */
    private Server server;


    public GrpcServer(Integer port,HelloServiceGrpc.HelloServiceImplBase service) {
        this(port,ServerBuilder.forPort(port),service);
    }

    public GrpcServer(Integer port, ServerBuilder builder,HelloServiceGrpc.HelloServiceImplBase service) {
        logger.info("init grpc server");
        // 通过serverbuild来初始化server
        server = builder.addService(service).build();
    }

    public void start() throws IOException {
        server.start();
        logger.info("start server");
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            logger.info("shut down grpc server because JVM is shuts down");
            try {
                GrpcServer.this.stop();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            logger.info("grpc server shut down");
        }));
    }

    /**
     * 关闭服务器，如果服务器关闭达到超时时间，则放弃
     * @throws InterruptedException
     */
    public void stop() throws InterruptedException {
        if (server != null) {
            // shut down grpc server
            server.shutdown().awaitTermination(30, TimeUnit.SECONDS);
        }
    }

    /**
     * 阻塞服务器，直到服务器关闭
     * @throws InterruptedException
     */
    public void blockUntilShutdown() throws InterruptedException {
        if (server != null) {
            // blocking grpc server
            server.awaitTermination();
        }
    }

    public static void main(String[] args) {
        try {
            GrpcServer server = new GrpcServer(13451, new GrpcService());
            server.start();
            server.blockUntilShutdown();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            // 启动服务器失败
            logger.info("failed to start server");
        }
    }
}
